<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<!-- <cl-add-btn /> -->
			<!-- 删除按钮 -->
			<!-- <cl-multi-delete-btn /> -->
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<el-card shadow="never" body-style="padding: 8px 12px;">
				<div style="font-size: 14px;">
					销售金额总览：￥{{ (totalAmount / 100).toFixed(2) }}
				</div>
			</el-card>
			<el-card shadow="never" body-style="padding: 8px 12px; margin-left: 12px;">
				<div style="font-size: 14px;">
					退款金额总览：￥{{ (refundAmountTotal / 100).toFixed(2) }}
				</div>
			</el-card>
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'order-order'
});

import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';

const { service } = useCool();

/* 所有商户 */
const allStore = ref<any[]>([]);

/* 获取所有role为2的用户 */
const getAgentList = async () => {
	const children = await service.user.info.list({
		role: 2
	});

	allStore.value = children?.map(_c => {
		return {
			label: `${_c.nickName ?? '-'} (手机号：${_c.phone})`,
			value: _c.id
		};
	});
};

getAgentList();

// 所有代理
const allAgent = ref<any[]>([]);

/* 获取所有代理 */
const getAllAgent = async () => {
	const children = await service.user.info.list({
		role: 1
	});

	allAgent.value = children?.map(_c => {
		return {
			label: `${_c.nickName ?? '-'} (手机号：${_c.phone})`,
			value: _c.id
		};
	});
};

getAllAgent();

const { t } = useI18n();
const totalAmount = ref<number>(0);
const refundAmountTotal = ref<number>(0);

// 选项
const options = reactive({
	payStatus: [
		{ label: t('待支付'), value: 0 },
		{ label: t('已支付'), value: 1, type: 'success' },
		{ label: t('已关闭'), value: 2, type: 'danger' },
		{ label: t('已退款'), value: 3, type: 'danger' }
	]
});

// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			label: t('订单编号'),
			prop: 'orderNo',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('支付金额'),
			prop: 'payAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('支付状态'),
			prop: 'payStatus',
			component: { name: 'el-radio-group', options: options.payStatus },
			value: 0,
			required: true
		},
		{
			label: t('支付时间'),
			prop: 'payTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('选择支付用户'),
			prop: 'payUserId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('设备号'),
			prop: 'deviceNo',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('选择设备归属人'),
			prop: 'deviceBindUserId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('退款原因'),
			prop: 'refundReason',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('退款时间'),
			prop: 'refundTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('是否完成投币'),
			prop: 'isComplete',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('套餐内容'),
			prop: 'packageContent',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		}
	]
});

// cl-table
const Table = useTable({
	columns: [
		{ type: 'selection' },
		{ label: t('订单编号'), prop: 'orderNo', minWidth: 120 },
		{ label: t('设备代理'), prop: 'deviceBindAgentNickName', minWidth: 120 },
		{ label: t('设备归属'), prop: 'deviceBindNickName', minWidth: 120 },
		{
			label: t('支付金额'),
			prop: 'payAmount',
			minWidth: 120,
			formatter: row => `￥${row.payAmount / 100}`
		},
		{
			label: t('支付状态'),
			prop: 'payStatus',
			minWidth: 120,
			dict: options.payStatus
		},
		// { label: t('支付用户ID'), prop: 'payUserId', minWidth: 120 },
		{ label: t('设备号'), prop: 'deviceNo', minWidth: 120 },
		{
			label: t('套餐内容'),
			prop: 'packageContent',
			minWidth: 120,
			render: _row => {
				const _packinfo = _row.packageContent ? JSON.parse(_row.packageContent) : undefined;

				return _packinfo
					? `${_packinfo?.packagePrice / 100}元 = ${_packinfo?.gameCount}币`
					: '无';
			}
		},
		{
			label: t('创建时间'),
			prop: 'createTime',
			minWidth: 170,
			sortable: 'desc',
			component: { name: 'cl-date-text' }
		},
		{
			type: 'op',
			buttons: ({ scope }) => [
				{
					label: '退款',
					type: 'success',
					hidden: scope?.row?.payStatus !== 1,
					onClick({ scope }) {
						console.log('scope', scope);
						// scope行数据

						/* 二次确认弹窗 */
						ElMessageBox.confirm(`是否退款？`, '提示', {
							type: 'error'
						})
							.then(() => {
								service.order.order
									.refund({
										orderNo: scope?.row?.orderNo
									})
									.then(res => {
										console.log('res', res);

										if (res?.code === 'BBS00000') {
											ElMessage.success('退款成功');

											// 刷新列表

											refresh();
										} else {
											ElMessage.error('退款失败');
										}
									})
									.catch(err => {
										console.log('err', err);
										ElMessage.error(err?.message);
									});
							})
							.catch(() => {
								console.log('取消');
							});
					}
				}
			],
			width: 80
		}
	]
});

// cl-search
const Search = useSearch({
	items: [
		{
			label: '状态',
			prop: 'payStatus',
			component: {
				name: 'el-select',
				options: [
					{
						label: '已支付',
						value: 1
					},
					{
						label: '未支付',
						value: 0
					}
				],
				props: {
					clearable: true
				}
			}
		},
		{
			label: '订单编号',
			prop: 'keyWord',
			component: {
				name: 'el-input'
			}
		},
		{
			label: '设备号',
			prop: 'deviceNo',
			component: {
				name: 'el-input'
			}
		},
		{
			label: '商户名称',
			prop: 'deviceBindUserId',
			component: {
				name: 'el-select',
				options: allStore,
				clearable: true,
				props: {
					clearable: true
				}
			}
		},
		{
			label: '代理名称',
			prop: 'deviceBindAgentId',
			component: {
				name: 'el-select',
				options: allAgent,
				clearable: true,
				props: {
					clearable: true
				}
			}
		},
		{
			label: '开始时间',
			prop: 'createTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss', clearable: true }
			}
		},
		{
			label: '结束时间',
			prop: 'endTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss', clearable: true }
			}
		}
	]
});

console.log('allAgent', allAgent);

// cl-crud
const Crud = useCrud(
    {
        service: service.order.order,
        async onRefresh(params, { next, render, done }) {
            const res = await next(params);
            render(res?.list);
            try {
                const sumRes = await service.order.order.request({
                    url: '/sum',
                    method: 'POST',
                    data: params
                });
                totalAmount.value = Number(sumRes?.total || 0);
                const refundRes = await service.order.order.request({
                    url: '/refundSum',
                    method: 'POST',
                    data: params
                });
                refundAmountTotal.value = Number(refundRes?.total || 0);
            } catch (e) {
                totalAmount.value = 0;
                refundAmountTotal.value = 0;
            }
            done();
        }
    },
    app => {
        app.refresh();
    }
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}
</script>
